#!/user/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/8/8 13:33
# @Author  : Leslie Wong
# @FileName: awesome-snake.py
# @Software: PyCharm

import pygame
import sys
import random
import time
import json

# 全局定义
SCREEN_X = 800
SCREEN_Y = 600


# 蛇类
# 点以25为单位
class Snake(object):
    # 初始化各种需要的属性 [开始时默认向右/身体块x5]
    def __init__(self):
        self.direction = pygame.K_UP
        self.defaultcolor = (0, 173, 181)
        self.colorPalette = [(0, 183, 194), (49, 143, 181), (70, 130, 180), (135, 206, 250), (135, 206, 235),
                             (173, 216, 230), (0, 206, 209)]
        self.body = []
        for x in range(5):
            self.addnode()

    # MOVE!
    def move(self):
        self.addnode()
        self.delnode()

    # 无论何时 都在前端增加蛇块
    def addnode(self):
        left, top = (400, 425)
        if self.body:
            left, top = (self.body[0].left, self.body[0].top)
        node = pygame.Rect(left, top, 25, 25)
        if self.direction == pygame.K_LEFT:
            node.left -= 25
        elif self.direction == pygame.K_RIGHT:
            node.left += 25
        elif self.direction == pygame.K_UP:
            node.top -= 25
        elif self.direction == pygame.K_DOWN:
            node.top += 25
        self.body.insert(0, node)

    # 删除最后一个块
    def delnode(self):
        self.body.pop()

    # 死亡判断
    def isdead(self):
        # 撞墙
        if self.body[0].x not in range(SCREEN_X):
            return True
        if self.body[0].y not in range(SCREEN_Y):
            return True
        # 撞自己
        if self.body[0] in self.body[1:]:
            return True
        return False

    # 改变方向 但是左右、上下不能被逆向改变
    def changedirection(self, curkey):
        LR = [pygame.K_LEFT, pygame.K_RIGHT]
        UD = [pygame.K_UP, pygame.K_DOWN]
        if curkey in LR + UD:
            if (curkey in LR) and (self.direction in LR):
                return
            if (curkey in UD) and (self.direction in UD):
                return
            self.direction = curkey


# 食物类
# 方法： 放置/移除
# 点以25为单位
class Food:
    def __init__(self):
        self.rect = pygame.Rect(-25, 0, 25, 25)
        self.defaultColor = (131,131,131)
        self.allposX = []
        self.allposY = []
        for posX in range(0, SCREEN_X - 25, 25):
            self.allposX.append(posX)
        for posY in range(0, SCREEN_Y - 25, 25):
            self.allposY.append(posY)

    def remove(self):
        self.rect.x = -25

    def set(self, snakebody):
        if self.rect.x == -25:
            # Not duplicate with snake body
            tempRect = pygame.Rect(-25, 0, 25, 25)
            tempRect.left = random.choice(self.allposX)
            tempRect.top = random.choice(self.allposY)
            while tempRect in snakebody:
                tempRect.left = random.choice(self.allposX)
                tempRect.top = random.choice(self.allposY)
            self.rect = tempRect
            print(self.rect)


class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  # call Sprite initializer
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location


def show_text(screen, pos, text, color, font_bold=False, font_size=60, font_type="gamer2", font_italic=False):
    # 获取系统字体，并设置文字大小
    # cur_font = pygame.font.SysFont("Microsoft YaHei UI", font_size)
    cur_font = pygame.font.Font(r"font\{}.ttf".format(font_type), font_size)
    # 设置是否加粗属性
    cur_font.set_bold(font_bold)
    # 设置是否斜体属性
    cur_font.set_italic(font_italic)
    # 设置文字内容
    text_fmt = cur_font.render(text, 1, color)
    # 绘制文字
    screen.blit(text_fmt, pos)


def main(isgamestart=False):
    # Initialize pygame
    pygame.init()
    BackGround = Background('img/background.png', [0, 0])
    screen_size = (SCREEN_X, SCREEN_Y)
    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption('Wandering Snake')
    clock = pygame.time.Clock()

    # Initialize game info
    scores = 0
    isdead = False
    rate = 10
    with open("data/highestScore.json", "r") as scoreFile:
        data = scoreFile.read()
    obj = json.loads(data)
    highestScore = int(obj["score"])

    # Instantiate Snake and Food
    snake = Snake()
    food = Food()

    # to display text periodically
    displayCounter = 0
    while True:
        # Initialize pygame background
        screen.fill((255, 255, 255))
        screen.blit(BackGround.image, BackGround.rect)

        # Player hasn't started game
        if not isgamestart:
            show_text(screen, (25, 120), 'Wandering Snake', (227, 29, 18), False, 70, "gamer2")
            if (displayCounter % 14) < 7:
                show_text(screen, (220, 520), 'press space to start', (192, 192, 192), False, 25, "gamer1")
            displayCounter += 1
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                    isgamestart = True
        # The game starts
        else:
            displayCounter = 0
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    snake.changedirection(event.key)
                    # fix the bug that it will cause false death
                    # when pressing direction key for two times at a fast rate
                    isdead = snake.isdead()
                    if event.key == pygame.K_SPACE and isdead:
                        # pass True to skip the welcome page
                        return main(True)

            # Render the snake
            for index, rect in enumerate(snake.body):
                if rate == 10:
                    pygame.draw.rect(screen, snake.defaultcolor, rect, 0)
                else:
                    # keep the color of head the same
                    if index == 0:
                        pygame.draw.rect(screen, snake.defaultcolor, rect, 0)
                    else:
                        pygame.draw.rect(screen, random.choice(snake.colorPalette), rect, 0)

            # Check Life State
            isdead = snake.isdead()

            # check game page state
            if not isdead:
                scores += 1
                snake.move()
            else:
                show_text(screen, (180, 220), 'YOU DEAD!', (213, 64, 98), False, 70, "gamer2")
                show_text(screen, (190, 520), 'press space to try again', (192, 192, 192), False, 25, "gamer1")
                if scores > highestScore:
                    highestScore = scores
                    saveScoreData = {"score": highestScore, "time": time.time()}
                    with open('data/highestScore.json', 'w') as targetFile:
                        json.dump(saveScoreData, targetFile)

            # Display Food
            food.set(snake.body)
            pygame.draw.rect(screen, food.defaultColor, food.rect, 0)

            # Eat food
            if food.rect == snake.body[0]:
                scores += 50
                food.remove()
                snake.addnode()

            # Display stat
            show_text(screen, (710, 20), f"{str(scores)}", (34, 40, 49), False, 18, "gamer1")
            show_text(screen, (580, 20), f"HI   {str(highestScore)}", (34, 40, 49), False, 18, "gamer1")

            # Boost Mode
            keys = pygame.key.get_pressed()  # checking pressed keys
            if keys[pygame.K_SPACE]:
                rate = 20
            else:
                rate = 10

        pygame.display.update()
        clock.tick(rate)


if __name__ == '__main__':
    main()
